<template>
	<el-form
		v-loading="isLoading"
		ref="tagForm"
		:inline="inline"
		:label-position="labelPosition"
		:label-width="labelWidth"
		:label-suffix="labelSuffix"
		:model="tagForm"
	>
		<el-form-item label="试题年份" prop="applicableYear">
			<el-select
				placeholder="请选择试题年份"
				clearable
				v-model="tagForm.applicableYear"
				:disabled="disablePropList.includes('试题年份')"
			>
				<el-option
					v-for="year in questionYear"
					:key="year.id"
					:label="year.name"
					:value="year.id"
				/>
			</el-select>
		</el-form-item>
		<el-form-item label="所属地区">
			<cascader-area
				ref="cascaderAreaRef"
				has-all-area
				v-model="tagForm.areaIds"
				:props-options="{ multiple: areaMultiple}"
				:disabled="disablePropList.includes('所属地区')"
				:params="{
					areaCode: '',
					rank: 2,
					needArea: 'N'
				}"
				@change="onAreaChange"
			/>
		</el-form-item>
		<!-- 动态展示标签 -->
		<el-form-item
			:label="label.labelName"
			v-show="isShow(label.labelName)"
			v-for="label in tagForm.labelList"
			:key="label.labelId"
		>
			<template #label>
				<span :title="label.labelName.length > 4 ? label.labelName: ''">{{ label.labelName }}</span>
			</template>
			<el-select
				:placeholder="'请选择'+label.labelName"
				clearable
				v-model="label.labelDetailId"
				:disabled="disablePropList.includes(label.labelName)"
				@change="handleChange(label, $event)"
			>
				<el-option
					v-for="item in labelOptionsData[label.labelId]"
					:key="item.labelDetailId"
					:label="item.labelDetailName"
					:value="item.labelDetailId"
				/>
			</el-select>
		</el-form-item>
	</el-form>
</template>
<script>
import tagApi from "@rc/apis/rc/tag.mjs";
	/**
	 * 涵盖标签信息的表单项
	 */
	import CascaderArea from "@rc/pages/components/async/cascader-area.vue";
	export default {
		props: {
            /**
             * 回显格式
             tagInfo：{
                applicableYear:'2022'
                areaIds:[cityId,cityId]
                labelList:{ 标签回显
                    labelId: xx,
                    labelDetailId:xxx
                }
             }
             */
            tagInfo:{
                type:Object,
                default:()=>{}
            },
			max: {
				/**控制修改max的值控制展开和收起隐藏 -1全部显示*/
				type: Number,
				default: -1
			},
            areaMultiple:{/*地区是否多选*/
                type: Boolean,
				default: false
            },
			inline: {/*同element-ui form表单 inline */
				type: Boolean,
				default: true
			},
			labelPosition: {/* 同element-ui form表单 labelPosition */
				type: String,
				default: ""
			},
            labelWidth:{/* 同element-ui form表单 labelWidth */
                type: String,
                default: ''
            },
			labelSuffix: {/* 同element-ui form表单 labelSuffix */
				type: String,
				default: ""
			},
			labelNameList: {/*年份和地区为固定选项,其他标签可配置 不传或空数组显示全部*/
				type: Array,
				default: () => []
			},
            disablePropList: {/*禁用的表单项 labelNameList中存在有效*/
                type: Array,
                default: () => []
		    },
            //设置初始值的标签属性 由于标签值不能写死，动态标签在获取标签信息后初始化
            initValuePropList:{
                type: Array,
                default: () => []
            }
		},
		components: {
			CascaderArea
		},
		created() {
			this.getQuestionYear();
            //设置所属地区初始值为全国
            if(this.initValuePropList.includes('所属地区')){
                this.tagForm.areaIds =['0000'];
            }
            //设置年份初始值为当前年
            if(this.initValuePropList.includes('试题年份')){
                this.tagForm.applicableYear = new Date().getFullYear()+'';
            }
		},
		data() {
			return {
                labelOptionsData:[],
				tagForm: { //标签表单数据
                    applicableYear:'',
                    labelList:[],
                    areaIds:[],
                    areaList:[]
                },
                questionYear:[]//试题年份
			};
		},
        computed:{//解决监听的表单信息新旧值相同的问题
            newTagData(){
                return JSON.parse(JSON.stringify(this.tagForm));
            }
        },
        watch:{
            tagInfo:{
               immediate:true,
                deep:true,
                handler(val) {
                    if(val){
                        this.tagForm = {
                            ...this.tagForm,
                            ...JSON.parse(JSON.stringify(val)),
                            labelList: []
                        };
                    }
                    this.getLabelDataInit();
                }
            },
            newTagData:{
                immediate:true,
                deep:true,
                handler(val){
                   this.$emit('change',val);
                }
            },
        },
		methods: {
			/**
	        控制表单项是否展示
	       */
			isShow(key) {
                if(this.max===-1){//不限制显示内容
                    return true;
                }
                if(!this.tagForm.labelList || !this.tagForm.labelList.length){
                    return false;
                }
				const index = this.tagForm.labelList.findIndex(label=>label.labelName===key);
				const isShow = index!==-1 && index < (this.max-2);
				return isShow;
			},
			/*
			 *获取所有的动态标签
			 */
			getLabelDataInit() {
                this.isLoading = true;
                tagApi.getResourceLabels({
                    data:{
                        applyScope: 'Q',// 题
                        labelType: 'S'// 系统标签
                    },
                    success:((labelsData) => {
                        let labelList = [];
                        let labelOptionsData = [];
                        if(this.labelNameList && this.labelNameList.length){
                            labelsData = labelsData.filter((item) => this.labelNameList.find((tagName) => tagName === item.labelName));
                        }

                        //判断是否有资源用途标签
                        labelsData.forEach((label) => {
                            let labelDetailId = '';
                            //标签初始值
                            if(this.initValuePropList.includes(label.labelName)){
                                labelDetailId = label.labelDetailInfosResponseVoList[0].labelDetailId;
                            }
                            //标签信息回显
                            if(this.tagInfo && this.tagInfo.labelList){
                                let labelInfo= this.tagInfo.labelList.find(item=>item.labelId === label.labelId);
                                if(labelInfo) {
                                    labelDetailId = labelInfo.labelDetailId;
                                }
                            }
                            labelList.push({
                                labelId: label.labelId,
                                labelDetailId,
                                labelName: label.labelName,
                            });
                            labelOptionsData[label.labelId] = label.labelDetailInfosResponseVoList;
                        });
                        this.labelOptionsData = labelOptionsData;
                        this.tagForm.labelList = labelList;
                        this.isLoading = false;
				    })
                });
			},
            getQuestionYear(){
                let date = new Date();
                let startYear = 2000;
                let nowYears = date.getFullYear();
                let endYear = nowYears+1;
                let arrYear = [];
                for (let i = endYear; i >= startYear; i--) {
                    arrYear.push({
                        id:i+'',
                        name:i+'年'
                    });
                }
                this.questionYear = arrYear;
            },
            onAreaChange(){
                if(!this.$refs.cascaderAreaRef){
                    return;
                }
                this.tagForm.areaList =  this.$refs.cascaderAreaRef.api_getAreaList();
            },
			/**
			 * 返回表单信息
			 */
			api_result() {
                this.onAreaChange();
                const {applicableYear, areaIds,labelList,areaList} = this.tagForm;
                //查询使用数据
				return {
                    areaIds,
                    areaList,
                    labelList: labelList.map(i => ({
                        ...i,
                        labelDetailName: i.labelDetailId ? this.labelOptionsData[i.labelId].find(i2 => i2.labelDetailId === i.labelDetailId).labelDetailName : ''
                    })),
                    applicableYear,
                };
			},
			/**
			 * 重置数据
			 */
			api_reset() {
				this.$refs.tagForm.resetFields();
                this.$refs.cascaderAreaRef && this.$refs.cascaderAreaRef.api_clearCheckedNodes();
                let labelList = this.tagForm.labelList.map((label)=>{
                    return {
                        labelId: label.labelId,
                        labelDetailId:'',
                        labelName: label.labelName,
                        labelDetailName: '',
                    };
                });
                this.tagForm = { //标签表单数据
                    applicableYear:'',
                    labelList,
                    areaIds:[],
                    areaList:[]
                };
			},
            handleChange(item, e) {
                item.labelDetailName = this.labelOptionsData[item.labelId].find(({ labelDetailId }) => labelDetailId === e).labelDetailName;
            },
		}
	};
</script>
<style lang="less" scoped>
    .el-form {
		display: flex;
		flex-wrap: wrap;
        /deep/ .el-form-item__content {
		    width: 210px;
	    }
        /deep/ .el-form-item__label {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
        .input-width{
            width: 100%;
        }
	}
</style>
